<template>
  <a-card :bordered="false">
    <div class="card-title">{{ $route.meta.title }}</div>
    <div class="table-operator">
      <a-row>
        <a-col :span="24">
          <a-button v-action:add type="primary" icon="plus" @click="handleAdd">新增</a-button>
          <a-button style="margin-left: 10px" @click="handleRefresh">刷新列表</a-button>
<!--          <a-button-->
<!--            v-action:qrcode-->
<!--            type="primary"-->
<!--            :disabled="selectedRowKeys.length===0"-->
<!--            @click="handlesxewm(true)"-->
<!--            style="margin-left: 10px">刷新二维码-->
<!--          </a-button>-->
<!--          <a-button-->
<!--            v-action:qrcode-->
<!--            type="danger"-->
<!--            :disabled="selectedRowKeys.length===0"-->
<!--            @click="handlety(true,1)"-->
<!--            style="margin-left: 10px">停用-->
<!--          </a-button>-->
<!--          <a-button-->
<!--            v-action:qrcode-->
<!--            type="primary"-->
<!--            :disabled="selectedRowKeys.length===0"-->
<!--            @click="handlety(true,0)"-->
<!--            style="margin-left: 10px">恢复正常-->
<!--          </a-button>-->
<!--          <a-button-->
<!--            v-action:qrcode-->
<!--            type="primary"-->
<!--            :disabled="selectedRowKeys.length===0"-->
<!--            @click="handlesxewm(true,1)"-->
<!--            style="margin-left: 10px">刷新二维码(同步)-->
<!--          </a-button>-->
<!--          <a-button-->
<!--            v-action:qrcode-->
<!--            type="danger"-->
<!--            :disabled="selectedRowKeys.length===0"-->
<!--            @click="handlety(true,1,1)"-->
<!--            style="margin-left: 10px">停用(同步)-->
<!--          </a-button>-->
<!--          <a-button-->
<!--            v-action:qrcode-->
<!--            type="primary"-->
<!--            :disabled="selectedRowKeys.length===0"-->
<!--            @click="handlety(true,0,1)"-->
<!--            style="margin-left: 10px">恢复正常(同步)-->
<!--          </a-button>-->
        </a-col>
        <!--        <a-col :span='12' :offset='10'>-->
        <!--          <a-input-search-->
        <!--            style='max-width: 300px; min-width: 150px;float: right;'-->
        <!--            v-model='queryParam.search'-->
        <!--            placeholder='请输入登录用户名 / 渠道商姓名'-->
        <!--            @search='onSearch'-->
        <!--          />-->
        <!--        </a-col>-->
      </a-row>
    </div>
    <s-table
      ref="table"
      rowKey="store_user_id"
      :loading="isLoading"
      :columns="columns"
      :data="loadData"
      :pageSize="15"
      tableLayout="auto"
      :scroll="{x:true}"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >
      <div slot="real_name" slot-scope="text, item">
        <a-tag v-if="item.status==0" color="green">正常</a-tag>
        <a-tag v-else color="red">停用</a-tag>
        <span style="margin-right: 6px">{{ text }}</span>
      </div>
      <div slot="user_name" slot-scope="text, item">
        <span style="margin-right: 6px">{{ text }}</span>
        <a-tag v-if="item.is_this" color="green">当前账号</a-tag>
      </div>
      <div slot="parentUser" slot-scope="text, item">
        {{ item.parentUser ? item.parentUser.real_name : '无' }}
      </div>
      <div slot="children_count" slot-scope="text, item">
        <a>{{ text }}</a>
      </div>
      <div class="actions" slot="action" slot-scope="text, item">
        <a-popover
          v-action:h5qrcode
          trigger="click">
          <template slot="content">
            <div
              style="text-align: center;background: #fff;padding: 20px 10px 20px 10px"
              :id="'qqqcode'+item.store_user_id">
              <div v-if="codeUrl" style="text-align: center;white-space: nowrap;">
                <a
                  style="padding:5px 10px;background:#e8e8e8;color: #a40000;border-radius: 6px"
                >{{ item.user_name }} - 在线考培系统</a>
              </div>
              <img v-if="codeUrl" :src="codeUrl" style="width: 150px;height: 150px;margin-top: 10px;">
              <div v-else style="text-align: center">
                <a-spin style="margin: 0 auto" />
              </div>
            </div>
            <div style="text-align:center">
              <a
                @click="downloadWxCode(item.user_name+' - 在线考培系统','qqqcode'+item.store_user_id)">下载二维码</a>
            </div>
          </template>
          <a @click="handleShowH5Code(item)">H5考试码</a>
        </a-popover>
        <a v-action:edit @click="handleEdit(item)">编辑</a>
        <a v-if="!item.is_super" v-action:delete @click="handleDelete(item)">删除</a>
      </div>
    </s-table>
    <AddForm ref="AddForm" :roleList="roleList" @handleSubmit="handleRefresh" />
    <EditForm ref="EditForm" :roleList="roleList" @handleSubmit="handleRefresh" />
  </a-card>
</template>

<script>
import * as Api from '@/api/store/user'
import * as RoleApi from '@/api/store/role'
import { STable } from '@/components'
import AddForm from './modules/AddForm'
import EditForm from './modules/EditForm'
import QRCode from 'qrcodejs2'
import html2canvas from 'html2canvas'
import store from '@/store'

const publicConfig = store.getters.publicConfig

export default {
  name: 'Index',
  components: {
    STable,
    AddForm,
    EditForm
  },
  data () {
    return {
      qrcode_type: 0,
      codeUrl: '',
      // 角色列表
      roleList: [],
      // 查询参数
      queryParam: {},
      // 正在加载
      isLoading: false,
      // 表头
      columns: [
        // {
        //   title: '',
        //   dataIndex: 'store_user_id'
        // },
        {
          title: '序号',
          dataIndex: 'no',
          key: 'no',
          customRender: (text, record, index) => `${index + 1}`
        },
        {
          title: '用户姓名',
          dataIndex: 'real_name',
          scopedSlots: { customRender: 'real_name' }
        },
        {
          title: '手机号码',
          dataIndex: 'phone'
        },
        {
          title: '公司名称',
          dataIndex: 'corporate_name'
        },
        {
          title: '登录用户名',
          dataIndex: 'user_name',
          scopedSlots: { customRender: 'user_name' }
        },
        {
          title: '上级渠道',
          dataIndex: 'parentUser.real_name',
          scopedSlots: { customRender: 'parentUser' }
        },
        {
          title: '下级渠道总数量',
          dataIndex: 'children_count',
          scopedSlots: { customRender: 'children_count' }
        },
        // {
        //   title: '二维码编号',
        //   dataIndex: 'h5_code_time'
        // },
        // {
        //   title: '添加时间',
        //   dataIndex: 'create_time'
        // },
        {
          fixed: 'right',
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: param => {
        return Api.list({ ...param, ...this.queryParam })
          .then(response => {
            return response.data.list
          })
      },

      selectedRowKeys: []
    }
  },
  created () {
    // 获取角色列表
    // this.getRoleList()
  },
  methods: {
    onSelectChange (selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    /**
     * 新增记录
     */
    handleAdd () {
      this.$refs.AddForm.add()
    },

    handlesxewm (item, tb = 0) {
      const app = this
      const userId = item === true ? this.selectedRowKeys : item.store_user_id
      const modal = this.$confirm({
        title: '您确定要刷新二维码?',
        content: '',
        onOk () {
          return Api.sxewm({ userId, tb })
            .then((result) => {
              app.$message.success(result.message, 1.5)
              app.handleRefresh()
              app.selectedRowKeys = []
            })
            .finally(result => {
              modal.destroy()
            })
        }
      })
    },

    handlety (item, status2 = 0, tb = 0) {
      const app = this
      const userId = item === true ? this.selectedRowKeys : item.store_user_id
      const status = item === true ? status2 : (item.status ? 0 : 1)
      const modal = this.$confirm({
        title: '您确定要执行当前操作?',
        content: '',
        onOk () {
          return Api.ty({ userId, status, tb })
            .then((result) => {
              app.$message.success(result.message, 1.5)
              app.handleRefresh()
              app.selectedRowKeys = []
            })
            .finally(result => {
              modal.destroy()
            })
        }
      })
    },

    /**
     * 编辑记录
     */
    handleEdit (item) {
      this.$refs.EditForm.edit(item)
    },

    /**
     * 获取角色列表
     */
    getRoleList () {
      this.isLoading = true
      RoleApi.list()
        .then(result => {
          this.roleList = result.data.list
        })
        .finally(() => {
          this.isLoading = false
        })
    },

    /**
     * 删除记录
     */
    handleDelete (item) {
      const app = this
      const modal = this.$confirm({
        title: '您确定要删除该记录吗?',
        content: '删除后不可恢复',
        onOk () {
          return Api.deleted({ userId: item['store_user_id'] })
            .then((result) => {
              app.$message.success(result.message, 1.5)
              app.handleRefresh()
            })
            .finally(result => {
              modal.destroy()
            })
        }
      })
    },

    /**
     * 刷新列表
     * @param Boolean bool 强制刷新到第一页
     */
    handleRefresh (bool = false) {
      this.$refs.table.refresh(bool)
    },

    /**
     * 检索查询
     */
    onSearch () {
      this.handleRefresh(true)
    },

    handleShowH5Code (item) {
      var element = document.createElement('div')
      var url = window.location.origin + '/h5/#/?channel_id=' + item.store_user_id + '&h5_code_time=' + item.h5_code_time
      const qrcode = new QRCode(element, {
        text: url,
        width: 200,
        height: 200,
        colorDark: '#333333',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.L
      })
      const canvas = qrcode._el.getElementsByTagName('canvas')[0]
      this.codeUrl = canvas.toDataURL()
    },
    downloadWxCode (filename, dom) {
      html2canvas(
        document.getElementById(dom),
        {
          // backgroundColor: null, // 画出来的图片有白色的边框,不要可设置背景为透明色（null）
          useCORS: true, // 支持图片跨域
          scale: 1// 设置放大的倍数
        }
      ).then(canvas => {
        const a = document.createElement('a')
        a.href = canvas.toDataURL('image/png')
        a.download = filename
        a.click()
      })
    }

  }
}
</script>
